package com.example.skillcinema.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.example.skillcinema.databinding.GalleryImageBinding
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.db.responses.ImageItemResponse
import com.example.skillcinema.viewholders.FilmItemViewHolder
import com.example.skillcinema.viewholders.GalleryImageItemViewHolder

class GalleryListPagedAdapter(
    val onClick: (imageUrl: String) -> Unit
) :
    PagingDataAdapter<ImageItemResponse, GalleryImageItemViewHolder>(GalleryDiffUtilCallback()) {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): GalleryImageItemViewHolder = GalleryImageItemViewHolder(
        GalleryImageBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    )

    override fun onBindViewHolder(
        holder: GalleryImageItemViewHolder,
        position: Int
    ) {
        val item = getItem(position)
        item?.let {
            with(holder.binding) {
                root.setOnClickListener {
                    onClick(item.imageUrl)
                }
                Glide.with(imageView)
                    .load(item.imageUrl)
                    .placeholder(android.R.drawable.progress_indeterminate_horizontal)
                    .error(android.R.drawable.stat_notify_error)
                    .into(imageView)
                val screenWidth = holder.itemView.context.resources.displayMetrics.widthPixels
                val layoutParams = holder.itemView.layoutParams
                layoutParams.width = if ((position + 1) % 3 == 0) screenWidth else screenWidth / 2
                holder.itemView.layoutParams = layoutParams
                val staggeredParams =
                    holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
                staggeredParams.isFullSpan = (position + 1) % 3 == 0
            }
        }
    }
}